<style scoped>
.container {
  padding: 16px 16px 16px 0;
  border: 1px solid #efefef;
}

.el-select .el-select--small {
  display: block !important;
}
</style>

<!-- 页面布局-->
<template>
  <div class="table">
    <!-- 主体区 -->
    <div class="container">
      <!-- 表单区 -->
      <div class="form-data-box">
        <el-form :model="formBean" :rules="validateRules" ref="form1" label-width="100px" class="ruleForm" style="width:90%;">
          <el-row>
            <el-col :span="12">
              <el-form-item label="省份" prop="provinceCode">
                <v-selectpage data="/rps/province/?isp=10010&pageRows=10&pageIndex=1" :params="{isp: '10010'}" :page-rows="10" key-field="provinceId" show-field="provinceName" :disabled="readOnly" :selected="formBean.provinceId" :result-format="resultFormat" :placeholder="formBean.provinceName || '请选择'" v-model="formBean.provinceId" @values="changeProvince" @removed="clearParameters('province')">
								</v-selectpage>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="号段" prop="dnsegNum">
                <el-select :disabled="readOnly" v-model="formBean.dnsegNum" clearable @focus="preSelDnesg" @change="changeDnesg">
                  <el-option v-for="item in dicts.dnseg" :key="item.dnsegNum" :label="item.dnsegNum" :value="item.dnsegNum">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="地市" prop="cityCode">
                <v-selectpage v-if="canChoseCity" :data="`/rps/city/?provinceId=${this.formBean.provinceId}`" :params="{provinceId: this.formBean.provinceId}" :page-rows="10" key-field="cityCode" show-field="cityName" :selected="formBean.cityCode" :result-format="resultFormat" :placeholder="formBean.cityName || '请选择'" @values="changeCity" @removed="clearParameters('city')">
								</v-selectpage>
                <el-select :disabled="true" v-else v-model="formBean.cityName" placeholder="地市" clearable class="handle-input mr10">
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="imsi数量">
                <el-input readonly v-model="imsiNum"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="卡商" prop="spNo">
                <v-selectpage data="/rps/sp/?isp=10010&pageRows=10&pageIndex=1" :disabled="readOnly || !canEditSp" :params="{isp: '10010'}" :page-rows="10" key-field="spNo" show-field="spName" :selected="formBean.spNo" :result-format="resultFormat" :placeholder="formBean.spName || '请选择'" @values="changeSp">
								</v-selectpage>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请数量" prop="cardNum">
                <el-input :readonly="readOnly" v-model="formBean.cardNum"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
             <el-col>
              <el-form-item label="产品名称" prop="productName">
                <el-input :readonly="readOnly" v-model="formBean.productName"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="版面描述" prop="cardFaceName">
                <v-selectpage data="/rps/cardFace/?isp=10010&pageRows=10&pageIndex=1" :disabled="readOnly" :params="{isp: '10010'}" :page-rows="10" key-field="cardFaceId" show-field="faceName" :selected="formBean.cardFaceId" :result-format="resultFormat" :placeholder="formBean.cardFaceName || '请选择'" @values="changeCardFace" :width="490">
								</v-selectpage>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 表单区END -->
      <!-- 按钮操作区 -->
      <span slot="footer" class="form-btn-box">
        <el-button v-if="!readOnly" type="primary" @click="submitForm('form1')" v-loading.fullscreen.lock="fullscreenLoading">保 存</el-button>
        <el-button @click="cnacelForm('form1')">取 消</el-button>
      </span>
      <!-- 按钮操作区END -->

    </div>
    <!-- 主体区END -->

    
  </div>
</template>
<script>
export default {
  data() {
    var validateCardNum = (rule, value, callback) => {
      var zg =  /^[0-9]{1,10}$/; 
      if (!zg.test(value) || Number(value) < 1) {
        callback(new Error("请输入大于0的数字"));
      } else {
        callback();
      }
    }
    var validateDnsegNum = (rule, value, callback) => {
      if(!this.formBean.provinceCode || !this.formBean.cityCode){
        callback(new Error("请先选择省市，再选择号段"));
      } else if (value == null || value == undefined || value == ""){
        callback(new Error("请选择号段"));
      } else {
        callback()
      }
    }
    return {
      // 提交表单的loading设置标识
      fullscreenLoading: false,
      firstLoadedData: "{}",
      // 新增用户表单信息
      formBean: {
        provinceCode: "", //省份
        cityCode: "", //地市
        spNo: "", //卡商
        dnsegNum: "", //号段
        productName: "", //产品名称
        cardNum: "", //申请数量
        cardFace: "",//版面描述
        cardFaceName: "" //版面描述
      },
      // 表单校验规则
      validateRules: {
        provinceCode: [
          { required: true, message: "请选择省份", trigger: "blur" }
        ],
        cityCode: [
          { required: true, message: "请选择城市", trigger: "blur" }
        ],
        spNo: [
          { required: true, message: "请选择卡商", trigger: "blur" }
        ],
        dnsegNum: [{ required: true, validator: validateDnsegNum, trigger: "blur" }],
        productName: [
          { required: true, message: "请输入产品名称", trigger: "blur" }
        ],
        cardNum: [
          { required: true, validator: validateCardNum, trigger: "blur" }
        ],
        cardFaceName: [
          { required: true, message: "请选择版面描述", trigger: "blur" }
        ]
      },
      canSelDnseg: false, //未选择省市时，不可以选择号段
      //所选记录id
      selectedId: "",
      //事物类型
      actType: "",
      // 表单只读状态
      readOnly: true,
      //字典集
      dicts: {},
      selectSp: null,
      seleSpNo: "",
      canEditSp: true,
      cardApplyBatchId: "",
      imsiNum: "",
			canChoseCity: false,
    };
  },
  props: {
    sourceData: {
      required: true
    }
  },
  // 进入页面加载数据
  mounted() {
    this.handleInitLoad();
  },
  methods: {
    /**
     * 组件初始化加载
     */
    handleInitLoad() {
      this.initSelectOptoins();
      this.initFormData();
    },

    /**
     * 初始加载字典选项
     */
    initSelectOptoins() {
      // this.loadSelectOptoins("province", {"isp":10010});
      // this.loadSelectOptoins("sp", {"isp":10010});
      // this.loadSelectOptoins("cardFace", {"isp":10010});
    },


    /**
     * 通用定义:下拉字典
     *  @augments dictKind 字典类型
     */
    loadSelectOptoins(dictKind, params) {
      let url = "/rps/" + dictKind + "/";
      this.$axios
      .get(url, {
        params: params,
        headers:{
          operator: this.$util.getLoginer().userid,
          withCredentials: true
        }
      })
      .then(res => {
        let data = res.data;
        if (data.success) {
          this.$set(this.dicts, dictKind, data.data.list);
        } else {
          this.$error( "查询失败" + data.message );
        }
      })
      .catch(err => {
        console.log(err);
      });
    },

    /**
     * 通用定义:下拉字典
     *  @augments dictKind 字典类型
     */
    promiseLoadSelectOptoins(dictKind, params) {
      return new Promise((resolve, reject)=>{
        let url = "/rps/" + dictKind + "/";
        this.$axios
        .get(url, {
          params: params,
          headers:{
            operator: this.$util.getLoginer().userid,
            withCredentials: true
          }
        })
        .then(res => {
          let data = res.data;
          if (data.success) {
            this.$set(this.dicts, dictKind, data.data.list);
            resolve(data.data.list);
          } else {
            reject("查询失败" + data.message );
          }
        })
        .catch(err => {
          reject("查询失败");
        });
      })
    },

    /**
     * 取消返回
     * @augments formName 表单名称
     */
    cnacelForm(formName) {
      this.$refs[formName].resetFields();
      this.$emit("cancel", null);
    },

    /**
     * 重置表单
     * @augments formName 表单名称
     */
    resetForm(formName) {
      this.formBean = JSON.parse(this.firstLoadedData);
      this.reSetProvince2City();
    },

    /**
     *初始化加载表单数据
     */
    initFormData() {
      this.selectedId = this.sourceData.seleid;
      this.actType = this.sourceData.actType;
      this.seleSpNo = this.sourceData.seleSpNo;
      if(this.seleSpNo != null && this.seleSpNo != undefined && this.seleSpNo != ""){
        this.canEditSp = false;
        this.formBean.spNo = this.seleSpNo;
        if(this.actType == "add"){
          this.reSetSp();
        }
      }
      if (this.actType == "view") {
        // 查看状态 标识表单只读
        this.readOnly = true;
        this.formBean = this.sourceData.item;
        this.firstLoadedData = JSON.stringify(this.formBean);
        // this.reSetProvince2City();
        // this.reSetSp();
        // this.reSetCardFace();
        this.reSetImsi();
      }else if(this.actType == "add"){
        this.readOnly = false;
      }else if(this.actType == "upd"){
        this.readOnly = false;
        this.formBean = this.sourceData.item;
        this.firstLoadedData = JSON.stringify(this.formBean);
        // this.reSetProvince2City();
        // this.reSetSp();
        // this.reSetCardFace();
        this.reSetImsi();
      }
    },

    reSetProvince2City(){
      if(this.dicts.province != null && this.dicts.province != undefined && this.dicts.province.length > 0){
        this.dicts.province.forEach(item=>{
          if(this.formBean.provinceCode == item.provinceCode){
            this.$set(this.formBean, "province", item);
            this.$set(this.formBean, "provinceCode", item.provinceCode);
            this.$set(this.formBean, "provinceName", item.provinceName);
            this.reSetCity(item.provinceId);
          }
        });
      }else{
        this.promiseLoadSelectOptoins("province", {"isp":10010}).then(data=>{
          data.forEach(item=>{
            if(this.formBean.provinceCode == item.provinceCode){
              this.$set(this.formBean, "province", item);
              this.$set(this.formBean, "provinceCode", item.provinceCode);
              this.$set(this.formBean, "provinceName", item.provinceName);
              this.reSetCity(item.provinceId);
            }
          });
        });
       
      }
    },

    reSetCity(provinceId){
      let params = {
        provinceId: provinceId
      }
      this.promiseLoadSelectOptoins("city", params).then(data =>{
        if(data != null && data != undefined && data.length > 0){
          data.forEach(item => {
            if(this.formBean.cityCode == item.cityCode){
              this.$set(this.formBean, "city", item);
              this.$set(this.formBean, "cityCode", item.cityCode);
              this.$set(this.formBean, "cityName", item.cityName);
              this.canSelDnseg = true;
            }
          });
        }
      });
    },

    reSetSp(){
      this.promiseLoadSelectOptoins("sp", { isp:10010, spNo: this.formBean.spNo}).then(data =>{
        if(data != null && data != undefined && data.length > 0){
          data.forEach(item => {
            if(this.formBean.spNo == item.spNo){
              this.$set(this.formBean, "sp", item);
              this.$set(this.formBean, "spNo", item.spNo);
              this.$set(this.formBean, "spName", item.spName);
            }
          });
        }
      });
    },

    reSetCardFace(){
      if(this.dicts.cardFace != null && this.dicts.cardFace != undefined && this.dicts.cardFace.length > 0){
        this.dicts.cardFace.forEach(item=>{
          if(this.formBean.cardFaceId == item.cardFaceId){
            this.$set(this.formBean, "cardFace", item);
            this.$set(this.formBean, "faceName", item.faceName);
          }
        });
      }else{
        this.promiseLoadSelectOptoins("cardFace", {"isp":10010}).then(data =>{
          if(data != null && data != undefined && data.length > 0){
            data.forEach(item => {
              if(this.formBean.cardFaceId == item.cardFaceId){
                this.$set(this.formBean, "cardFace", item);
                this.$set(this.formBean, "faceName", item.faceName);
              }
            });
          }
        });
      }
    },

    reSetImsi(){
      this.changeDnesg(this.formBean.dnsegNum);
    },

    /**
     * 提交表单
     * @augments formName 表单名称
     */
    submitForm(formName) {
      //
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 表单校验成功
          if (this.actType == "upd") {
            //
            // 开启提交表单的loading
            this.fullscreenLoading = true;
            var url = "/rps/cardApplyDetail/"+this.formBean.cardApplyDetailId+"/";
            this.$axios
              .put(url, this.formBean, {
                headers: {
                  operator: this.$util.getLoginer().userid,
                  withCredentials: true
                }
              })
              .then(res => {
                let data = res.data;
                // 关闭提交表单的loading
                this.fullscreenLoading = false;
                if (data.success) {
                  this.$message({
                    message: "修改成功.",
                    type: "success"
                  });
                  this.$emit("ok", {});
                } else {
                  this.$error(data.message);
                }
              })
              .catch(err => {
                this.fullscreenLoading = false;
              });
          }else if(this.actType == "add"){
            //
            // 开启提交表单的loading
            this.fullscreenLoading = true;
            var url = "/rps/cardApplyBatch/"+ this.selectedId +"/cardApplyDetail/";
            this.$axios
              .post(url, this.formBean, {
                headers: {
                  operator: this.$util.getLoginer().userid,
                  withCredentials: true
                }
              })
              .then(res => {
                let data = res.data;
                // 关闭提交表单的loading
                this.fullscreenLoading = false;
                if (data.success) {
                  this.$message({
                    message: "数据保存成功.",
                    type: "success"
                  });
                  this.$emit("ok", {});
                } else {
                  this.$error(data.message);
                }
              })
              .catch(err => {
                this.fullscreenLoading = false;
              });
          }
        } else {
          // 表单校验失败
          // this.$error("数据校验失败.");
        }
      });
    },

    changeProvince(res){
      if(res && res.length > 0){
				let province = res[0];
        this.$set(this.formBean, "provinceCode", province.provinceCode);
        this.$set(this.formBean, "provinceName", province.provinceName);
        this.$set(this.formBean, "cityCode", "");
        this.$set(this.formBean, "cityName", "");
        this.$set(this.formBean, "dnsegNum", "");
        this.imsiNum = "";
				this.canChoseCity = true;
			}
    },

    changeCity(res){
      if(res && res.length > 0){
        let city = res[0];
        this.$set(this.formBean, "cityName", city.cityName);
        this.$set(this.formBean, "cityCode", city.cityCode);
        this.$delete(this.formBean, "dnsegNum");
        this.imsiNum = "";
        this.canSelDnseg = true;
      }
    },

    changeSp(res){
      if(res && res.length > 0){
        let sp = res[0];
        this.$set(this.formBean, "spNo", sp.spNo);
        this.$set(this.formBean, "spName", sp.spName);
      }
    },

    changeCardFace(res){
      if(res && res.length > 0){
        let cardFace = res[0];
        this.$set(this.formBean, "cardFaceName", cardFace.faceName);
        this.$set(this.formBean, "cardFaceId", cardFace.cardFaceId);
      }
    },
    
    preSelDnesg(){
      this.$refs['form1'].validateField(['provinceCode','cityCode'], err => {
        if (err) {
          this.canSelDnseg = false;
          return;
        }
        this.canSelDnseg = true;
        let params = {
          provinceCode: this.formBean.provinceCode,
          cityCode: this.formBean.cityCode
        }
        this.loadSelectOptoins("dnseg", params);
      })
    },

    changeDnesg(dnesg) {
      this.$axios.get("/rps/dnseg/" + dnesg + "/imsiFree/",{
        headers:{
          operator: this.$util.getLoginer().userid,
          withCredentials: true
        }
      }).then(res => {
        let data = res.data;
        if(data.success){
          this.imsiNum = data.data;
        }else{
          this.$message(data.message);
        }
      }).catch(err => {
        console.log(err);
      })
    },
     /**
		 * v-selectpage 格式化参数数据
		 */
		resultFormat(resp){
			let data = resp.data;
			 if(data.success){
				return {
					totalRow: data.data ? data.data.count : 0,
					list: data.data ? data.data.list : []
				};
			 } else {
				return {
					totalRow: 0,
					list: []
				};
			 }
    },
    clearParameters(name){
			if(name == "province"){
				this.$delete(this.formBean, "provinceCode");
				this.$delete(this.formBean, "provinceId");
        this.$delete(this.formBean, "provinceName");
        this.$delete(this.formBean, "cityCode");
        this.$delete(this.formBean, "cityName");
        this.$delete(this.formBean, "dnsegNum");
        this.imsiNum = '';
        this.canChoseCity = false;
        this.canSelDnseg = false;
			}else if(name == "city"){
				this.$delete(this.formBean, "cityCode");
        this.$delete(this.formBean, "cityName");
        this.$delete(this.formBean, "dnsegNum");
        this.imsiNum = '';
        this.canSelDnseg = false;
			}
		}

  }
};
</script>
